import { Directive } from 'vue'

export const vDraggable: Directive = {
  mounted(el: HTMLElement) {
    el.style.cursor = 'move'
    el.style.userSelect = 'none'
    
    el.onmousedown = (e: MouseEvent) => {
      const disX = e.clientX - el.offsetLeft
      const disY = e.clientY - el.offsetTop
      
      document.onmousemove = (e: MouseEvent) => {
        el.style.left = e.clientX - disX + 'px'
        el.style.top = e.clientY - disY + 'px'
      }
      
      document.onmouseup = () => {
        document.onmousemove = null
        document.onmouseup = null
      }
    }
  }
}

// 使用方式: <div v-draggable style="position: absolute;"></div>